package com.meta.hibernate;

import java.util.List;

import lombok.extern.slf4j.Slf4j;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Slf4j
@Service
public class HibernateUtil {

	@Autowired
	private SessionFactory sessionFactory;

	/**
	 * 重建SessionFactory
	 */

	public Session getSession(){
		Session session = null;
		try{
			session = sessionFactory.openSession();
		} catch( Exception e ){
			log.error(e.getMessage(),e);
		}
		return session;
	}

	/**
	 * 	关闭session
	 * @param session
	 */
	public void closeSession( Session session ){
		
		try{
			if ( session != null )
				session.close();//这里不能关闭SessionFactory，因为SessionFactory是全局对象		
		}catch ( Exception e ){
			log.error(e.getMessage(),e);
		}
	}
	/**
	 * 回滚事务
	 * @param transaction
	 */
	public static void rollbackTransaction(Transaction transaction){
		try{
			if ( null != transaction )
				transaction.rollback();
		}catch ( Exception e ){
			log.error(e.getMessage(),e);
		}
	}
	
	/**
	 * 执行hql，启动事务
	 * @param hql
	 * @return
	 */
	
	public List exeQuery(String hql){
		List list = null;
		Transaction transaction = null;
		Session session = null;
		try{
			session = this.getSession();
			transaction = session.beginTransaction();
			list = session.createQuery(hql).list();
			transaction.commit();
		}catch (HibernateException he ){
			he.printStackTrace();
			HibernateUtil.rollbackTransaction(transaction);
		}catch ( Exception e ){
			log.error(e.getMessage(),e);
		}finally{
			this.closeSession(session);			
		}
		return list;
	}
}
